package br.brpv.silvestrin.vendas.loginactivity;

import android.app.Activity;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import br.brpv.silvestrin.vendas.R;
import br.brpv.silvestrin.vendas.domain.User;
import br.brpv.silvestrin.vendas.mainactivity.MainActivity;
import br.brpv.silvestrin.vendas.settingsactivity.SettingsWebserviceFragment;
import br.brpv.silvestrin.vendas.util.ShowMessage;
import br.brpv.silvestrin.vendas.webservice.ServerDataCacheService;
import br.brpv.silvestrin.vendas.settingsactivity.SettingsActivity;
import br.brpv.silvestrin.vendas.webservice.ServerConnection;

public class LoginActivity extends Activity implements View.OnClickListener {

    private static final String LOGIN_USER_PASSWORD = "loginUserAndPassword";
    private static final String LOGIN_USER = "loginUser";
    private static final String LOGIN_PASSWORD = "loginPassword";
    private static final String LOGIN_REMEMBER_USER = "loginRememberUser";
    private static final String LOGIN_REMEMBER_PASSWORD = "loginRememberPassword";

    public static final String USER_EXTRA = "user";

    private ServerDataCacheService mServerDataCacheBinder;
    private boolean mBound;

    /** Called when the activity is first created. */

    private enum status {
        SUCCESS, FAIL
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);


        Button login = (Button) findViewById(R.id.btnLogin);
        if(login != null) login.setOnClickListener(this);

        SharedPreferences preferences = this.getSharedPreferences(LOGIN_USER_PASSWORD, Activity.MODE_WORLD_WRITEABLE);

        CheckBox rememberUserCheckBox = (CheckBox)findViewById(R.id.remember_user);
        CheckBox rememberPasswordCheckBox = (CheckBox)findViewById(R.id.remember_password);

        rememberUserCheckBox.setChecked(preferences.getBoolean(LOGIN_REMEMBER_USER, false));
        rememberPasswordCheckBox.setChecked(preferences.getBoolean(LOGIN_REMEMBER_PASSWORD, false));

        if(rememberUserCheckBox.isChecked() || rememberPasswordCheckBox.isChecked()){
            EditText userName = (EditText)findViewById(R.id.login_user);
            userName.setText(preferences.getString(LOGIN_USER, ""));

            if(rememberPasswordCheckBox.isChecked()){
                EditText userPassword = (EditText)findViewById(R.id.login_password);
                userPassword.setText(preferences.getString(LOGIN_PASSWORD, ""));
            }
        }

        TextView version = (TextView)findViewById(R.id.version_text);
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            version.setText("Version - " + pInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }


        Intent intent = new Intent(this, ServerDataCacheService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onStop();
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            ServerDataCacheService.LocalBinder localBinder = (ServerDataCacheService.LocalBinder)iBinder;

            mServerDataCacheBinder = localBinder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.login_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_launch_calc:

                Intent i = new Intent("org.openintents.action.CALCULATOR");
                try {
                    startActivity(i);
                } catch (Exception e) {
                    i = new Intent();
                    i.setClassName("com.android.calculator2",
                            "com.android.calculator2.Calculator");
                    try{
                        startActivity(i);
                    }catch (Exception e1) {
                        i = new Intent();
                        i.setClassName("com.sec.android.app.popupcalculator",
                                "com.sec.android.app.popupcalculator.Calculator");
                        try{
                            startActivity(i);
                        } catch (Exception e2){
                            ShowMessage.alertDialog(this, R.string.missing_calculator);
                        }
                    }
                }
                break;

            case R.id.menu_settings:
                Intent iSettings = new Intent(getApplicationContext(),
                        SettingsActivity.class);
                startActivity(iSettings);
                break;

            case R.id.menu_exit:
                finish();
                break;
        }
        return true;
    }


    private status initializeServer() {
        SharedPreferences preferences = getSharedPreferences(SettingsWebserviceFragment.WEB_SERVICE_PREFERENCES, MODE_WORLD_READABLE);
        String serverUrl = preferences.getString(SettingsWebserviceFragment.SERVER_URL,"");
        if(serverUrl.equalsIgnoreCase("")) return status.FAIL;
        String serverUser = preferences.getString(SettingsWebserviceFragment.SERVER_USER, "");
        if(serverUser.equalsIgnoreCase("")) return status.FAIL;
        String serverPass = preferences.getString(SettingsWebserviceFragment.SERVER_PASSWORD, "");
        if(serverPass.equalsIgnoreCase("")) return status.FAIL;

        ServerConnection.setParameters(serverUrl, serverUser, serverPass);
        return status.SUCCESS;
    }

    @Override
    public void onClick(View view) {
        EditText user = (EditText) findViewById(R.id.login_user);
        EditText pass = (EditText) findViewById(R.id.login_password);
        SharedPreferences preferences = getSharedPreferences(LOGIN_USER_PASSWORD, Activity.MODE_WORLD_WRITEABLE);
        SharedPreferences.Editor editor = preferences.edit();

        CheckBox rememberUserCheckBox = (CheckBox)findViewById(R.id.remember_user);
        CheckBox rememberPasswordCheckBox = (CheckBox)findViewById(R.id.remember_password);

        editor.putBoolean(LOGIN_REMEMBER_USER, rememberUserCheckBox.isChecked());
        editor.putBoolean(LOGIN_REMEMBER_PASSWORD, rememberPasswordCheckBox.isChecked());

        editor.commit();

        if(initializeServer() == status.FAIL) ShowMessage.alertDialog(this, R.string.login_server_disconfigured);
        else {
            ServerConnection.selectUser(user.getText().toString(), pass.getText().toString(), this);

        }
    }

    public void  onSelectUser(User user){
        if(user == null){
            ShowMessage.alertDialog(this, R.string.login_authentication_fail);
        }else {
            SharedPreferences preferences = this.getSharedPreferences(LOGIN_USER_PASSWORD, Activity.MODE_WORLD_WRITEABLE);
            SharedPreferences.Editor editor = preferences.edit();

            EditText userLogon = (EditText)findViewById(R.id.login_user);
            editor.putString(LOGIN_USER, userLogon.getText().toString());
            EditText userPassword = (EditText)findViewById(R.id.login_password);
            editor.putString(LOGIN_PASSWORD, userPassword.getText().toString());

            editor.commit();

            mServerDataCacheBinder.setCurrentUser(user);

            Intent i = new Intent(getApplicationContext(),
                    MainActivity.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            i.putExtra(USER_EXTRA, user);
            startActivity(i);
        }

    }

    public void onSelectUserServerError() {
        ShowMessage.alertDialog(this, R.string.wsmessage_server_unreachable);
    }

}